import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:lite_message/obj/user.dart';
import 'package:lite_message/util/app_util.dart';
import 'package:lite_message/util/data_util.dart';

///网络请求封装
class DioUtil {
  static Dio _dio = Dio();

  ///接口地址
  static const String _API = "http://api.liugl.cn:5555";
  // static const String _API = "http://192.168.1.6:5555";

  ///注册接口
  static const String _SIGNUP = "/api/signup";

  ///登录接口
  static const String _SIGNIN = "/api/signin";

  ///get请求
  static const String _GET = "GET";

  ///post请求
  static const String _POST = "POST";

  ///token
  static String _token = '';

  ///获取内部token
  static String get getToken => _token;

  ///刷新/设置内部token
  static void setToken(String newToken) => _token = newToken;

  ///请求通道
  static Future<Map<String, dynamic>> request(
      BuildContext context, Map data, String api,
      {String mothed = _POST}) async {
    ///加载框是否打开
    bool _openLoading = false;

    try {
      ///主动取消焦点
      LM.unFocus(context);

      ///主动取消请求
      bool _handleClose = false;

      ///显示加载框
      LM.showLoading(context, onCancel: () async {
        _handleClose = true;
        _dio.clear();
        Navigator.pop(context, false);
      });
      _openLoading = true;

      LM.log('请求地址:${_API + api}');
      LM.log('请求类型:[$mothed]');
      LM.log('请求参数:${json.encode(data)}');

      final Response _r = await _dio.request(
        _API + api,
        data: data,
        options: Options(
          method: mothed,
          headers: {
            "token": _token,
            "Content-Type": "multipart/form-data",
          },
        ),
      );

      LM.log("返回结果:${_r.data}");

      ///主动取消返回空信息
      if (_handleClose) return {};

      ///如果没有主动关闭加载框，则自动关闭
      if (!_handleClose) Navigator.pop(context);

      return json.decode(_r.data);
    } catch (e) {
      ///如果请求在打开加载框后失败，则关闭加载框
      if (_openLoading) Navigator.pop(context, false);

      throw e;
    }
  }

  ///登录
  static Future<User> login(BuildContext context, Map data) async {
    try {
      await request(context, data, _SIGNIN);

      return User();
    } catch (e) {
      LM.log('登录出错:$e', type: 2);
      return null;
    }
  }

  ///注册
  static Future<User> regist(BuildContext context, Map data) async {
    try {
      final Map _r = await request(context, data, _SIGNUP);

      if (_r['code'] == 200) return User();

      LM.t(_r['msg']);
      return null;
    } catch (e) {
      LM.log('注册出错:$e', type: 2);
      return null;
    }
  }

  ///获取验证码
  static Future<bool> getCode(BuildContext context, String email) async {
    try {
      LM.log('开始验证邮箱:$email');

      await request(context, {"email": email}, '');

      return DataUtil.isEmail(email);
    } catch (e) {
      return false;
    }
  }

  ///设置新密码
  static Future<bool> setNewPsw(BuildContext context, Map data) async {
    try {
      LM.log('开始验证信息:$data');

      await request(context, data, '');

      return true;
    } catch (e) {
      return false;
    }
  }
}
